<?php

namespace app\shop\controller;

use think\Controller;

// 引入FastAdmin自带的一个邮箱发送类
use app\common\library\Email;

class Business extends Controller
{
    protected $BusinessModel;
    protected $PayModel;
    protected $RecordModel;

    public function __construct()
    {
        parent::__construct();

        $this->BusinessModel = model('Business.Business');
        $this->PayModel = model('pay.Pay');
        $this->RecordModel = model('Business.Record');
    }

    public function index()
    {
        return 1;
    }
    // 注册
    public function register()
    {
        if ($this->request->isPost()) {
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');

            if (empty($mobile) || empty($password)) {
                $this->error('手机号或密码不能为空');
            }

            // 生成一个密码盐
            $salt = randstr();

            // 对密码进行加密
            $password = md5($password . $salt);

            // 组装数据
            $data = [
                'mobile' => $mobile,
                'nickname' => $mobile,
                'password' => $password,
                'salt' => $salt,
                'gender' => '0', //性别
                'deal' => '0', //成交状态
                'money' => '0', //余额
                'auth' => '0', //实名认证
            ];

            // 查询客户来源id
            $sourceid = model('common/Business/Source')->where(['name' => ['LIKE', "%家居商城%"]])->value('id');

            if ($sourceid) {
                $data['sourceid'] = $sourceid;
            }

            $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

            if ($result === false) {
                // 失败
                $this->error($this->BusinessModel->getError());
                exit;
            } else {
                // 注册成功条状登录页
                $this->success('注册成功', '/business/login');
                exit;
            }
        }
    }
    // 登录
    public function login()
    {
        if ($this->request->isPost()) {
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');

            $ckeck = $this->BusinessModel->where(['mobile' => $mobile])->find();

            if (!$ckeck) {
                $this->error('手机号或密码错误');
                exit;
            }

            $salt = $ckeck['salt'];
            $password = md5($password . $salt);

            if ($ckeck['password'] != $password) {
                $this->error('手机号或密码错误');
                exit;
            }

            unset($ckeck['password']);
            unset($ckeck['salt']);

            $this->success('登录成功', '/business/index', $ckeck);

            exit;
        }

        return $this->view->fetch();
    }
    // 验证登录
    public function check()
    {
        $id = $this->request->param('id', '', 'trim');
        $mobile = $this->request->param('mobile', '', 'trim');

        $business = $this->BusinessModel->where(['id' => $id, 'mobile' => $mobile])->find();

        if ($business) {

            unset($business['password']);
            unset($business['salt']);

            $this->success('验证成功', null, $business);

            exit;
        } else {
            $this->error('验证失败');
            exit;
        }
    }
    // 基本信息
    public function profile()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', '', 'trim');

            $business = $this->BusinessModel->where(['id' => $id])->find();

            if (empty($business)) {
                $this->error('未知用户');
                exit;
            }

            $data = [
                'id'       => $id,
                'nickname' => $this->request->param('nickname', '', 'trim'),
                'mobile'   => $this->request->param('mobile', '', 'trim'),
                'gender'   => $this->request->param('gender', '', 'trim'),
            ];

            $email = $this->request->param('email', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $code = $this->request->param('code', '', 'trim');

            // 如果用户输入了密码，就修改密码
            if (!empty($password)) {
                // 重新生成密码盐
                $salt = randstr();

                $data['salt'] = $salt;
                $data['password'] = md5($password . $salt);
            }

            // 如果用户修改了邮箱，就取消认证
            if ($email != $business['email']) {
                $data['email'] = $email;
                $data['auth'] = '0';
            }
            // 用户是否选择地区
            if (!empty($code)) {
                $parentpath = model('Region')->where(['code' => $code])->value('parentpath');

                if (!empty($parentpath)) {
                    $arr = explode(',', $parentpath);

                    $data['province'] = isset($arr[0]) ? $arr[0] : null;
                    $data['city'] = isset($arr[1]) ? $arr[1] : null;
                    $data['district'] = isset($arr[2]) ? $arr[2] : null;
                }
            }
            // 判断是否有图片上传
            if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0) {
                $result = upload_image('avatar');

                if (!$result['success']) {
                    $this->error($result['msg']);
                    exit;
                }

                $data['avatar'] = $result['data'];
            }

            // 更新数据
            $result = $this->BusinessModel->validate('common/Business/Business.profile')->isUpdate(true)->save($data);

            // 写入数据库失败
            if ($result = false) {
                $this->error($this->BusinessModel->getError());
                exit;
            }

            // 判断是否有旧图片，有则删除
            if (isset($data['avatar'])) {
                $old_avatar = '.' . $business['avatar'];
                is_file($old_avatar) && @unlink($old_avatar);
            }

            $this->success('更新资料成功', '/business/index');
            exit;
        }
    }
    // 邮箱验证
    public function email()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', '', 'trim');
            $action = $this->request->param('action', '', 'trim');

            $EmsModel = model('common/Ems');

            $business = $this->BusinessModel->where(['id' => $id])->find();

            if (empty($business)) {
                $this->error('未知用户');
                exit;
            }

            //获取用户信息
            $email = empty($business['email']) ? '' : trim($business['email']);

            if (empty($email)) {
                $this->error('邮箱地址为空');
                exit;
            }

            if ($action == "send") {
                // 生成验证码
                $code = randstr(6);
                // 开始事务
                $EmsModel->startTrans();
                // 删除之前的验证码记录
                $EmsModel->where(['email' => $email])->delete();
                // 组装数据
                $data = [
                    'event' => 'auth',
                    'email' => $email,
                    'code' => $code,
                    'times' => 0,
                ];
                // 插入数据
                $result = $EmsModel->save($data);

                if ($result === false) {
                    $this->error('邮件发送失败');
                    exit;
                }

                // 实例化邮箱验证类
                $PhpMailer = new Email;

                $name = config('site.name');
                $subject = "【{$name}】邮箱验证";
                $message = "<div>您的邮箱验证码为：<b>$code</b></div>";

                $result = $PhpMailer
                    ->to($email)
                    ->subject($subject)
                    ->message($message)
                    ->send();

                if ($result) {
                    // 提交事务
                    $EmsModel->commit();
                    $this->success('验证码发送成功，请注意查收');
                    exit;
                } else {
                    // 回滚事务
                    $EmsModel->rollback();
                    $this->error($PhpMailer->getError());
                    exit;
                }
            } else {
                // 获取验证码
                $code = $this->request->param('code', '', 'trim');

                if (empty($code)) {
                    $this->error('验证码不能为空');
                    exit;
                }

                $EmsModel->startTrans();
                $this->BusinessModel->startTrans();

                $where = ['email' => $email, 'code' => $code];
                // 查询验证码
                $check = $EmsModel->where($where)->find();

                if (!$check) {
                    $this->error('验证码错误');
                    exit;
                }
                // 组装数据
                $data = [
                    'id'   => $id,
                    'auth' => '1',
                ];

                // 更新认证状态
                $busResult = $this->BusinessModel->isUpdate(true)->save($data);

                if ($busResult === false) {
                    $this->error('更新认证状态失败');
                }

                // 删除验证码
                $EmsResult = $EmsModel->where($where)->delete();

                if ($EmsResult === false) {
                    $this->BusinessModel->rollback();
                    $this->error('验证码记录删除失败');
                    exit;
                }

                if ($busResult === false || $EmsResult === false) {
                    $EmsModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->error('验证失败');
                    exit;
                } else {
                    $EmsModel->commit();
                    $this->BusinessModel->commit();
                    $this->success('验证成功');
                    exit;
                }
            }
        }
    }
    // 钱包信息
    public function wallet()
    {
        if ($this->request->isGet()) {
            $id = $this->request->param('id', '', 'trim');

            $business = $this->BusinessModel->where(['id' => $id])->find();

            if (empty($business)) {
                $this->error('未知用户');
                exit;
            }

            $data = [
                'money' => $business['money'],
                'pay' => 0,
                'record' => 0,
            ];

            $payList = $this->PayModel->select();

            $payList2 = [];

            if (!empty($payList)) {
                foreach ($payList as $v) {
                    $third = json_decode($v['third']);
                    if (intval($third->busid) === intval($id)) {
                        $payList2[] = $v;

                        // 把支付成功的加入累计充值
                        if($v['status'] === '1'){
                            $data['pay'] = bcadd($data['pay'], $v['price'], 2);
                        }
                    }
                }

                $data['payList'] = $payList2;
            } else {
                $data['payList'] = [];
            }

            $recordList = $this->RecordModel->where(['busid' => $id])->select();

            if (!empty($recordList)) {
                foreach ($recordList as $v) {
                    if (isNegativeNumber($v['total'])) {
                        $data['record'] = bcadd($data['record'], convertToPositiveNumber($v['total']), 2);
                    }
                }
            }

            $this->success('ok', '', $data);
        }
    }
    // 充值
    public function pay()
    {
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', 0, 'trim');
            $money = $this->request->param('money', 1, 'trim');
            $type = $this->request->param('type', 'wx', 'trim');


            // 判断用户是否存在
            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            if ($money <= 0) {
                $this->error('充值金额不能小于0元');
                exit;
            }


            // 发送一个接口请求出去
            $host = config('site.cdnurl');
            $host = trim($host, '/');

            // 完整的请求接口地址
            $api = $host . "/pay/index/create";

            // 订单支付完成后跳转的界面
            $reurl = "http://shop.xdlayman.cn/#/business/pay";

            $callbackurl = $host . "/shop/business/callback";

            // 携带一个自定义的参数过去 转换为json类型
            $third = json_encode(['busid' => $busid]);

            // 微信收款码
            $wxcode = config('site.wxcode');
            $wxcode = $host . $wxcode;

            // 支付宝收款码
            $zfbcode = config('site.zfbcode');
            $zfbcode = $host . $zfbcode;

            // 充值信息
            $PayData = [
                'name' => '余额充值',
                'third' => $third,
                'originalprice' => $money,
                //微信支付
                // 'paytype' => 0,
                // 'paypage' => 1,
                //支付宝支付
                // 'paytype' => 1,
                // 'paypage' => 2,
                'paypage' => 0,
                'wxcode' => $wxcode,
                'zfbcode' => $zfbcode,
                'reurl' => $reurl,
                'callbackurl' => $callbackurl,
            ];

            // 要看是哪一种支付方式
            if ($type == 'wx') {
                //微信
                $PayData['paytype'] = 0;
            } else {
                //支付宝
                $PayData['paytype'] = 1;
            }

            // 发起请求
            $result = httpRequest($api, $PayData);

            // 有错误
            if (isset($result['code']) && $result['code'] == 0) {
                $this->error($result['msg']);
                exit;
            }

            //将json转换为php数组
            $result = json_decode($result, true);

            $this->success('生成付款码', null, $result['data']);
            exit;
        }
    }
    // 查询支付订单订单是否成功
    public function query()
    {
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', 0, 'trim');
            $payid = $this->request->param('payid', '', 'trim');

            // 判断用户是否存在
            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            if (empty($payid)) {
                $this->error('支付记录不存在');
                exit;
            }

            //发送一个接口请求出去
            $host = config('site.cdnurl');
            $host = trim($host, '/');

            // 完整的请求接口地址
            $api = $host . "/pay/index/status";

            //发起请求
            $result = httpRequest($api, ['payid' => $payid]);

            // 将json转换为php数组
            $result = json_decode($result, true);

            if (isset($result['code']) && $result['code'] == 0) {
                $this->error($result['msg']);
                exit;
            } else {
                $status = isset($result['data']['status']) ? $result['data']['status'] : 0;
                $this->success('查询充值状态', null, ['status' => $status]);
                exit;
            }
        }
    }
    //充值回调
    public function callback()
    {
        // 判断是否有post请求过来
        if ($this->request->isPost()) {
            // 获取到所有的数据
            $params = $this->request->param();

            // 充值的金额
            $price = isset($params['price']) ? $params['price'] : 0;
            $price = floatval($price);

            // 第三方参数(可多参数)
            $third = isset($params['third']) ? $params['third'] : '';

            // json字符串转换数组
            $third = json_decode($third, true);

            // 从数组获取充值的用户id
            $busid = isset($third['busid']) ? $third['busid'] : 0;

            // 支付方式
            $paytype = isset($params['paytype']) ? $params['paytype'] : 0;

            // 支付订单id
            $payid = isset($params['id']) ? $params['id'] : 0;

            $pay = $this->PayModel->find($payid);

            if (!$pay) {
                return json(['code' => 0, 'msg' => '支付订单不存在', 'data' => null]);
            }

            $payment = '';

            switch ($paytype) {
                case 0:
                    $payment = '微信支付';
                    break;
                case 1:
                    $payment = '支付宝支付';
                    break;
            }

            // 判断充值金额
            if ($price <= 0) {
                return json(['code' => 0, 'msg' => '充值金额为0', 'data' => null]);
            }

            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                return json(['code' => 0, 'msg' => '充值用户不存在', 'data' => null]);
            }

            // 开启事务
            $this->BusinessModel->startTrans();
            $this->RecordModel->startTrans();

            // 转成浮点类型
            $money = floatval($business['money']);

            // 余额 + 充值的金额
            $updateMoney = bcadd($money, $price, 2);

            // 封装用户更新的数据
            $BusinessData = [
                'id' => $business['id'],
                'money' => $updateMoney
            ];

            // 自定义验证器
            $validate = [
                [
                    'money' => ['number', '>=:0'],
                ],
                [
                    'money.number' => '余额必须是数字类型',
                    'money.>=' => '余额必须大于等于0元'
                ]
            ];

            // 更新用户余额
            $BusinessStatus = $this->BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

            if ($BusinessStatus === false) {
                return json(['code' => 0, 'msg' => $this->BusinessModel->getError(), 'data' => null]);
            }

            // 封装插入消费记录的数据
            $RecordData = [
                'total' => $price,
                'content' => "{$payment}充值了 $price 元",
                'busid' => $business['id']
            ];

            // 插入消费记录
            $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

            if ($RecordStatus === false) {
                $this->BusinessModel->rollback();
                return json(['code' => 0, 'msg' => $this->RecordModel->getError(), 'data' => null]);
            }

            if ($BusinessStatus === false || $RecordStatus === false) {
                $this->BusinessModel->rollback();
                $this->RecordModel->rollback();
                return json(['code' => 0, 'msg' => '充值失败', 'data' => null]);
            } else {
                $this->BusinessModel->commit();
                $this->RecordModel->commit();

                // 订单号：\r\n
                // 金额:50元
                // 支付方式：
                // 时间，
                return json(['code' => 1, 'msg' => '充值成功', 'data' => null]);
            }
        }
    }
    // 消费记录
    public function record()
    {
        if ($this->request->isAjax()) {
            $page = $this->request->get('page', 1);
            $limit = $this->request->get('limit', 10);
            $busid = $this->request->param('busid', '', 'trim');

            $business = $this->BusinessModel->where(['id' => $busid])->find();

            if (empty($business)) {
                $this->error('未知用户');
                exit;
            }

            $offset = ($page - 1) * $limit;

            $where = [
                'busid' => $busid,
            ];

            $count = $this->RecordModel
                ->where($where)
                ->limit($offset, $limit)
                ->count();

            $list = $this->RecordModel
                ->where($where)
                ->order('createtime', 'desc')
                ->limit($offset, $limit)
                ->select();

            $data = [
                'list' => $list,
                'count' => $count,
            ];

            $this->success('ok', null, $data);
            exit;
        }
    }
}
